/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador.autogenerats;

import controlador.autogenerats.exceptions.IllegalOrphanException;
import controlador.autogenerats.exceptions.NonexistentEntityException;
import entity.Camp;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.Productor;
import entity.Produccio;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author David
 */
public class CampJpaController implements Serializable {

    public CampJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Camp camp) {
        if (camp.getProduccioCollection() == null) {
            camp.setProduccioCollection(new ArrayList<Produccio>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Productor productorId = camp.getProductorId();
            if (productorId != null) {
                productorId = em.getReference(productorId.getClass(), productorId.getId());
                camp.setProductorId(productorId);
            }
            Collection<Produccio> attachedProduccioCollection = new ArrayList<Produccio>();
            for (Produccio produccioCollectionProduccioToAttach : camp.getProduccioCollection()) {
                produccioCollectionProduccioToAttach = em.getReference(produccioCollectionProduccioToAttach.getClass(), produccioCollectionProduccioToAttach.getId());
                attachedProduccioCollection.add(produccioCollectionProduccioToAttach);
            }
            camp.setProduccioCollection(attachedProduccioCollection);
            em.persist(camp);
            if (productorId != null) {
                productorId.getCampCollection().add(camp);
                productorId = em.merge(productorId);
            }
            for (Produccio produccioCollectionProduccio : camp.getProduccioCollection()) {
                Camp oldCampIdOfProduccioCollectionProduccio = produccioCollectionProduccio.getCampId();
                produccioCollectionProduccio.setCampId(camp);
                produccioCollectionProduccio = em.merge(produccioCollectionProduccio);
                if (oldCampIdOfProduccioCollectionProduccio != null) {
                    oldCampIdOfProduccioCollectionProduccio.getProduccioCollection().remove(produccioCollectionProduccio);
                    oldCampIdOfProduccioCollectionProduccio = em.merge(oldCampIdOfProduccioCollectionProduccio);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Camp camp) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Camp persistentCamp = em.find(Camp.class, camp.getId());
            Productor productorIdOld = persistentCamp.getProductorId();
            Productor productorIdNew = camp.getProductorId();
            Collection<Produccio> produccioCollectionOld = persistentCamp.getProduccioCollection();
            Collection<Produccio> produccioCollectionNew = camp.getProduccioCollection();
            List<String> illegalOrphanMessages = null;
            for (Produccio produccioCollectionOldProduccio : produccioCollectionOld) {
                if (!produccioCollectionNew.contains(produccioCollectionOldProduccio)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Produccio " + produccioCollectionOldProduccio + " since its campId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (productorIdNew != null) {
                productorIdNew = em.getReference(productorIdNew.getClass(), productorIdNew.getId());
                camp.setProductorId(productorIdNew);
            }
            Collection<Produccio> attachedProduccioCollectionNew = new ArrayList<Produccio>();
            for (Produccio produccioCollectionNewProduccioToAttach : produccioCollectionNew) {
                produccioCollectionNewProduccioToAttach = em.getReference(produccioCollectionNewProduccioToAttach.getClass(), produccioCollectionNewProduccioToAttach.getId());
                attachedProduccioCollectionNew.add(produccioCollectionNewProduccioToAttach);
            }
            produccioCollectionNew = attachedProduccioCollectionNew;
            camp.setProduccioCollection(produccioCollectionNew);
            camp = em.merge(camp);
            if (productorIdOld != null && !productorIdOld.equals(productorIdNew)) {
                productorIdOld.getCampCollection().remove(camp);
                productorIdOld = em.merge(productorIdOld);
            }
            if (productorIdNew != null && !productorIdNew.equals(productorIdOld)) {
                productorIdNew.getCampCollection().add(camp);
                productorIdNew = em.merge(productorIdNew);
            }
            for (Produccio produccioCollectionNewProduccio : produccioCollectionNew) {
                if (!produccioCollectionOld.contains(produccioCollectionNewProduccio)) {
                    Camp oldCampIdOfProduccioCollectionNewProduccio = produccioCollectionNewProduccio.getCampId();
                    produccioCollectionNewProduccio.setCampId(camp);
                    produccioCollectionNewProduccio = em.merge(produccioCollectionNewProduccio);
                    if (oldCampIdOfProduccioCollectionNewProduccio != null && !oldCampIdOfProduccioCollectionNewProduccio.equals(camp)) {
                        oldCampIdOfProduccioCollectionNewProduccio.getProduccioCollection().remove(produccioCollectionNewProduccio);
                        oldCampIdOfProduccioCollectionNewProduccio = em.merge(oldCampIdOfProduccioCollectionNewProduccio);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = camp.getId();
                if (findCamp(id) == null) {
                    throw new NonexistentEntityException("The camp with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Camp camp;
            try {
                camp = em.getReference(Camp.class, id);
                camp.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The camp with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Produccio> produccioCollectionOrphanCheck = camp.getProduccioCollection();
            for (Produccio produccioCollectionOrphanCheckProduccio : produccioCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Camp (" + camp + ") cannot be destroyed since the Produccio " + produccioCollectionOrphanCheckProduccio + " in its produccioCollection field has a non-nullable campId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Productor productorId = camp.getProductorId();
            if (productorId != null) {
                productorId.getCampCollection().remove(camp);
                productorId = em.merge(productorId);
            }
            em.remove(camp);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Camp> findCampEntities() {
        return findCampEntities(true, -1, -1);
    }

    public List<Camp> findCampEntities(int maxResults, int firstResult) {
        return findCampEntities(false, maxResults, firstResult);
    }

    private List<Camp> findCampEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Camp.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Camp findCamp(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Camp.class, id);
        } finally {
            em.close();
        }
    }

    public int getCampCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Camp> rt = cq.from(Camp.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
